#include "stdafx.h"
#include "FxThread.h"
#include "MainInstance.h"
#include "FFMpegInstance.h"
#include "LogFileWriter.h"
#include "XMLInstance.h"
#include "GlobalInfoInstance.h"
#include "GlobalMemoryInstance.h"
#include "StreamSource.h"
#include "IPCameraStreamSource.h"
#include "WebCameraStreamSource.h"

CMainInstance::CMainInstance(void)
{
}

CMainInstance::~CMainInstance(void)
{
}

void CMainInstance::Run(void* This)
{
	// get working directory path
	char str_current_directory[1024] = {0};
	GetModuleFileNameA(NULL, str_current_directory, 1024);
	int i = strlen(str_current_directory);
	for (; i > 0; i--)
	{
		if (str_current_directory[i] == '\\' 
			|| str_current_directory[i] == '/')
		{
			str_current_directory[i] = '\0';
			break;
		}
	}

	strcpy(g_WorkDir, str_current_directory);

	__INFO("Main process is starting...");

	__DEBUG("Current work directory - '%s'", str_current_directory);

	CFFMpegInstance::GetInstance();
	CGlobalInfoInstance::GetInstance()->g_bln_isClosing = FALSE;
	
	CGlobalInfoInstance* ptr_global_instance = CGlobalInfoInstance::GetInstance();
	CGlobalMemoryInstance* ptr_global_memory_instance = CGlobalMemoryInstance::GetInstance();

	// generate stream-source object
	while (ptr_global_instance->g_ary_input_devices.Size() != 0)
	{
		CStreamSource* ptr_stream_source = NULL;
		INPUT_DEVICE* ptr_input_device = (INPUT_DEVICE*)ptr_global_instance->g_ary_input_devices.Get(0);
		if (ptr_input_device == NULL)
		{
			ptr_global_instance->g_ary_input_devices.Remove(0);
		}

		if (ptr_input_device->type == STREAM_INPUT_WEBCAM)
		{
			ptr_stream_source = new CWebCameraStreamSource();

		}
		else if (ptr_input_device->type == STREAM_INPUT_IPCAMERA)
		{
			ptr_stream_source = new CIPCameraStreamSource();
		}

		ptr_stream_source->m_ptr_input_device = ptr_input_device;

		ptr_global_instance->g_ary_input_devices.Set(0, NULL);
		ptr_global_instance->g_ary_input_devices.Remove(0);

		if (ptr_stream_source)
		{
			int int_stream_id = ptr_global_instance->GetMaxStreamID();
			CFrameBuffer* ptr_frame_buffer = ptr_global_memory_instance->AllocateFrameBuffer(int_stream_id);
			ptr_stream_source->SetRelationship(ptr_frame_buffer);
			ptr_global_memory_instance->DetachFrameBuffer(ptr_frame_buffer);
		}
	}

	while (isRunning)
	{
		for (int i = 0; i < ptr_global_memory_instance->GetSize(); i++)
		{
			CFrameBuffer* ptr_frame_buffer = ptr_global_memory_instance->AttachFrameBufferByIndex(i);
			if (ptr_frame_buffer->m_ptr_stream_source != NULL)
			{
				if (((CStreamSource*)ptr_frame_buffer->m_ptr_stream_source)->m_ptr_stream_receiver == NULL)
					((CStreamSource*)ptr_frame_buffer->m_ptr_stream_source)->StartStreamReceiver();
			}
			ptr_global_memory_instance->DetachFrameBuffer(ptr_frame_buffer);
		}

		Sleep(100);
	}
	__INFO("Main process is stopped.");
}
